<?php
/*
  This page combines a lot of the smarts from the intro pages into one stop.
  goResults() is the key function that comes from the cals js and checkGoalsSelected()
  causes the controls to be reordered based on the weight the user gives to each.
*/
?>

<?php
  if (!isset($_COOKIE['ys-parcelNum'])) {
    setcookie('noParcelNum',true);
    $u = explode('/',$_SERVER['REQUEST_URI']);
    array_pop($u);
    $u = 'http://'.$_SERVER['SERVER_NAME'].implode('/',$u).'/?page=introLocation';
    header('Location: '.$u);
  }
  $isRegistered = isset($_SESSION['gdusername']) AND isset($_SESSION['gdpassword']);

  $thumbnail = 'img/blank.png';
  if (isset($_COOKIE['ys-parcelThumbnail'])) {
    $thumbnail = substr($_COOKIE['ys-parcelThumbnail'],2);
  }
?>
  <body onload="Ext.onReady(function(){init()})">
    <script>
      var cp;
      var goals = {};
      var stormwaterControlThumbPanel;
      var stormwaterControlThumbDataView;
      var stormwaterControlTypeStore;
      var stormwaterControlTypeStoreStatic;
      var loadReductionPctField;
      var stormwaterControlConstraintComboBox;
      var parcelResultsGrid;
      var parcelInfoStore;
      var thumbDetailsWindowLastPos;

      function init() {
        Ext.get('loading').fadeOut({duration : 0.2,remove : true});
        Ext.QuickTips.init();

        cp = new Ext.state.CookieProvider({
          expires : new Date(new Date().getTime()+(1000*60*60*24*30)) //30 days
        });
        Ext.state.Manager.setProvider(cp);

        Ext.override(Ext.grid.PropertyGrid, {
            initComponent : function(){
                this.customRenderers = this.customRenderers || {};
                this.customEditors = this.customEditors || {};
                this.lastEditRow = null;
                var store = new Ext.grid.PropertyStore(this);
                this.propStore = store;
                var cm = new Ext.grid.PropertyColumnModel(this, store);
                // no sorting, dammit!
                // store.store.sort('name', 'ASC');
                this.addEvents(
                    /**
                     * @event beforepropertychange
                     * Fires before a property value changes.  Handlers can return false to cancel the property change
                     * (this will internally call {@link Ext.data.Record#reject} on the property's record).
                     * @param {Object} source The source data object for the grid (corresponds to the same object passed in
                     * as the {@link #source} config property).
                     * @param {String} recordId The record's id in the data store
                     * @param {Mixed} value The current edited property value
                     * @param {Mixed} oldValue The original property value prior to editing
                     */
                    'beforepropertychange',
                    /**
                     * @event propertychange
                     * Fires after a property value has changed.
                     * @param {Object} source The source data object for the grid (corresponds to the same object passed in
                     * as the {@link #source} config property).
                     * @param {String} recordId The record's id in the data store
                     * @param {Mixed} value The current edited property value
                     * @param {Mixed} oldValue The original property value prior to editing
                     */
                    'propertychange'
                );
                this.cm = cm;
                this.ds = store.store;
                Ext.grid.PropertyGrid.superclass.initComponent.call(this);

                        this.mon(this.selModel, 'beforecellselect', function(sm, rowIndex, colIndex){
                    if(colIndex === 0){
                        this.startEditing.defer(200, this, [rowIndex, 1]);
                        return false;
                    }
                }, this);
            }
        });

        stormwaterControlTypeStore = initBmpTypeStore();
        stormwaterControlTypeStoreStatic = initBmpTypeStore();
        var stormwaterControlConstraintStore = initBmpConstraintStore();
        var performanceStore = initPerformanceStore();

        // create a fake parcelInfoStore based on cookies
        parcelInfoStore = new Ext.data.ArrayStore({
          fields : [
             'Regulated'
            ,'Owner Name'
            ,'Dep2HWT (in)'
            ,'Dep2ResLyr (in)'
            ,'Hyd Soil Group'
            ,'KSat (in/hr)'
            ,'Imperv Area (ac)'
            ,'UpLand Area (ac)'
            ,'Wetland Area (ac)'
            ,'Total Area (ac)'
            ,'Perv Load (lb/yr)'
            ,'Imperv Load'
            ,'Total Load (lb/yr)'
            ,'Slope (%)'
            ,'Load Credit/Deficit (lb/yr)'
          ]
          ,data : [[
             cp.get('parcelRegulated')
            ,cp.get('parcelOwner Name')
            ,cp.get('parcelDep2HWT (in)')
            ,cp.get('parcelDep2ResLyr (in)')
            ,cp.get('parcelHyd Soil Group')
            ,cp.get('parcelKSat (in/hr)')
            ,cp.get('parcelImperv Area (ac)')
            ,cp.get('parcelUpLand Area (ac)')
            ,cp.get('parcelWetland Area (ac)')
            ,cp.get('parcelTotal Area (ac)')
            ,cp.get('parcelPerv Load (lb/yr)')
            ,cp.get('parcelImperv Load')
            ,cp.get('parcelTotal Load (lb/yr)')
            ,cp.get('parcelSlope (%)')
            ,cp.get('parcelLoad Credit/Deficit (lb/yr)')
          ]]
        });

        // Initialize all the goals and their weights.
        var goalsDiv = [
           '<div id="goals">'
          ,'<table id="bmpGoals">'
          ,'<tr><td class="bmpName">Aesthetic</td><td><div id="goalAesthetic" class="bmpRadio"></div></td></tr>'
          ,'<tr><td class="bmpName">TSS/Metals&nbsp;Reduction</td><td><div id="goalTssMetalsReduction" class="bmpRadio"></div></td></tr>'
          ,'<tr><td class="bmpName">Phosophorus&nbsp;Reduction</td><td><div id="goalPhosphorusReduction" class="bmpRadio"></div></td></tr>'
          ,'<tr><td class="bmpName">Nitrogen&nbsp;Reduction</td><td><div id="goalNitrogenReduction" class="bmpRadio"></div></td></tr>'
          ,'<tr><td class="bmpName">Bacteria&nbsp;Reduction</td><td><div id="goalBacteriaReduction" class="bmpRadio"></div></td></tr>'
          ,'<tr><td class="bmpName">Peak&nbsp;Flow&nbsp;Reduction</td><td><div id="goalPeakFlowReduction" class="bmpRadio"></div></td></tr>'
          ,'<tr><td class="bmpName">Volume&nbsp;Reduction</td><td><div id="goalVolumeReduction" class="bmpRadio"></div></td></tr>'
          ,'</table>'
          ,'</div>'
        ];

        goals['goalAesthetic'] = new Ext.form.RadioGroup({
           columns : [55,75,50]
          ,items   : [
             {boxLabel : 'High'  ,name : 'goalAesthetic',inputValue : 3}
            ,{boxLabel : 'Medium',name : 'goalAesthetic',inputValue : 2}
            ,{boxLabel : 'Low'   ,name : 'goalAesthetic',inputValue : 1}
          ]
          ,listeners : {change : function(radioGroup,checked) {
            checkGoalsSelected(goals,parcelInfoStore,stormwaterControlTypeStore);
          }}
        });
        goals['goalTssMetalsReduction'] = new Ext.form.RadioGroup({
           columns : [55,75,50]
          ,items   : [
             {boxLabel : 'High'  ,name : 'goalTssMetalsReduction',inputValue : 3}
            ,{boxLabel : 'Medium',name : 'goalTssMetalsReduction',inputValue : 2}
            ,{boxLabel : 'Low'   ,name : 'goalTssMetalsReduction',inputValue : 1}
          ]
          ,listeners : {change : function(radioGroup,checked) {
            checkGoalsSelected(goals,parcelInfoStore,stormwaterControlTypeStore);
          }}
        });
        goals['goalPhosphorusReduction'] = new Ext.form.RadioGroup({
           columns : [55,75,50]
          ,items   : [
             {boxLabel : 'High'  ,name : 'goalPhosphorusReduction',inputValue : 3}
            ,{boxLabel : 'Medium',name : 'goalPhosphorusReduction',inputValue : 2}
            ,{boxLabel : 'Low'   ,name : 'goalPhosphorusReduction',inputValue : 1}
          ]
          ,listeners : {change : function(radioGroup,checked) {
            checkGoalsSelected(goals,parcelInfoStore,stormwaterControlTypeStore);
          }}
        });
        goals['goalNitrogenReduction'] = new Ext.form.RadioGroup({
           columns : [55,75,50]
          ,items   : [
             {boxLabel : 'High'  ,name : 'goalNitrogenReduction',inputValue : 3}
            ,{boxLabel : 'Medium',name : 'goalNitrogenReduction',inputValue : 2}
            ,{boxLabel : 'Low'   ,name : 'goalNitrogenReduction',inputValue : 1}
          ]
          ,listeners : {change : function(radioGroup,checked) {
            checkGoalsSelected(goals,parcelInfoStore,stormwaterControlTypeStore);
          }}
        });
        goals['goalBacteriaReduction'] = new Ext.form.RadioGroup({
           columns : [55,75,50]
          ,items   : [
             {boxLabel : 'High'  ,name : 'goalBacteriaReduction',inputValue : 3}
            ,{boxLabel : 'Medium',name : 'goalBacteriaReduction',inputValue : 2}
            ,{boxLabel : 'Low'   ,name : 'goalBacteriaReduction',inputValue : 1}
          ]
          ,listeners : {change : function(radioGroup,checked) {
            checkGoalsSelected(goals,parcelInfoStore,stormwaterControlTypeStore);
          }}
        });

        goals['goalPeakFlowReduction'] = new Ext.form.RadioGroup({
           columns : [55,75,50]
          ,items   : [
             {boxLabel : 'High'  ,name : 'goalPeakFlowReduction',inputValue : 3}
            ,{boxLabel : 'Medium',name : 'goalPeakFlowReduction',inputValue : 2}
            ,{boxLabel : 'Low'   ,name : 'goalPeakFlowReduction',inputValue : 1}
          ]
          ,listeners : {change : function(radioGroup,checked) {
            checkGoalsSelected(goals,parcelInfoStore,stormwaterControlTypeStore);
          }}
        });
        goals['goalVolumeReduction'] = new Ext.form.RadioGroup({
           columns : [55,75,50]
          ,items   : [
             {boxLabel : 'High'  ,name : 'goalVolumeReduction',inputValue : 3}
            ,{boxLabel : 'Medium',name : 'goalVolumeReduction',inputValue : 2}
            ,{boxLabel : 'Low'   ,name : 'goalVolumeReduction',inputValue : 1}
          ]
          ,listeners : {change : function(radioGroup,checked) {
            checkGoalsSelected(goals,parcelInfoStore,stormwaterControlTypeStore);
          }}
        });

        // How to present each stormwater control thumbnail and label.
        var tpl = new Ext.XTemplate(
           '<tpl for=".">'
          ,'<div class="thumb-wrap" id="{name}">'
          ,'<div class="thumb"><img id="info.{short}" src="images/{short}.png" title="{full}" usemap="#{short}Map"></div>'
          ,'<map id="{short}Map" name="{short}Map"><area id="area.info.{short}" shape="rect" coords="63,43,80,60" href="javascript:;" alt="View control details" title="View control details"></area></map>'
          ,'<span class="x-editable">{fullBr}({overallScore}%){extraBr}</span></div>'
          ,'</tpl>'
          ,'<div class="x-clear"></div>'
        );
        stormwaterControlThumbDataView = new Ext.DataView({
           tpl          : tpl
          ,singleSelect : true
          ,store        : stormwaterControlTypeStore
          ,mode         : 'local'
          ,overClass    : 'x-view-over'
          ,itemSelector : 'div.thumb-wrap'
          ,listeners    : {
            selectionchange : function(dv,nodes) {
              goResults(parcelInfoStore,stormwaterControlThumbDataView,loadReductionPctField,stormwaterControlConstraintComboBox);
              var stormwaterControlTypeVal;
              var i = stormwaterControlThumbDataView.getSelectedIndexes();
              if (i.length >= 1) {
                stormwaterControlTypeVal = stormwaterControlTypeStore.getAt(i[0]).get('full');
              }
              var idx = stormwaterControlTypeStoreStatic.find('full',stormwaterControlTypeVal);
              if (idx >= 0) {
                loadReductionPctField.setValue(parcelInfoStore.getAt(0).get('Regulated') == 'True' ? 65 : 10);
              }
            }
            ,click : function(dv,nodeIdx,node,e) {
              var p = String(e.target.id).split('area.info.');
              if (p.length == 2) {
                var rec = stormwaterControlTypeStore.getAt(nodeIdx);
                showThumbDetailsWindow(rec.get('full'),rec.get('detailsHTML'),Ext.getCmp('solutionPanel').getPosition()[0] - 30,Ext.getCmp('solutionPanel').getPosition()[1] + 20,475);
              }
            }
          }
        });

        stormwaterControlThumbPanel = new Ext.Panel({
           layout   : 'fit'
          ,border   : false
          ,disabled : true
          ,items    : stormwaterControlThumbDataView
        });

        loadReductionPctField = new Ext.form.NumberField({
           allowNegative    : false
          ,decimalPrecision : 4
          ,minValue         : 0.00001
          ,maxValue         : 100
          ,width            : 125
          ,fieldLabel       : 'Load Reduction (%)'
          ,labelStyle       : 'font-family : Arial,Verdana,Helvetica,sans-serif;;font-size : 12px;;color : #069403;font-weight : bold;'
          ,disabled         : true
          ,listeners        : {valid : function() {
            goResults(parcelInfoStore,stormwaterControlThumbDataView,loadReductionPctField,stormwaterControlConstraintComboBox);
          }}
        });

        stormwaterControlConstraintComboBox = new Ext.form.ComboBox({
           store          : stormwaterControlConstraintStore
          ,displayField   : 'full'
          ,editable       : false
          ,triggerAction  : 'all'
          ,mode           : 'local'
          ,width          : 175
          ,fieldLabel     : 'Site Constraint'
          ,labelStyle     : 'font-family : Arial,Verdana,Helvetica,sans-serif;;font-size : 12px;;color : #069403;font-weight : bold;'
          ,forceSelection : true
          ,disabled       : true
          ,listeners      : {valid : function() {
            goResults(parcelInfoStore,stormwaterControlThumbDataView,loadReductionPctField,stormwaterControlConstraintComboBox);
          }}
        });

        var addlSiteConstraints = new Ext.FormPanel({
           border         : false
          ,labelWidth     : 145
          ,labelSeparator : ''
          ,id             : 'siteConstraints'
          ,items          : [loadReductionPctField,stormwaterControlConstraintComboBox]
        });

        parcelResultsGrid = new Ext.grid.PropertyGrid({
           autoHeight       : true
          ,loadMask         : true
          ,hideHeaders      : true
          ,border           : false
          ,width            : 355
          ,customRenderers  : {
             'Stormwater Control Total Cost ($)'      : function(v) {return '<span class="highlightTitle">' + v + '</span>';}
            ,'Stormwater Control Unit Cost ($/lb/yr)' : function(v) {return '<span class="highlightTitle">' + v + '</span>';}
          }
          ,listeners        : {
            'render'     : function(grid) {
              grid.getColumnModel().setColumnWidth(0,300);
            }
            ,'beforeedit' : function(e) {
              return false;
            }
            ,'show'      : function() {
              // When starting up, perform calcs so that we're looking at a fresh screen.
              var stormwaterControlTypeVal;
              var i = stormwaterControlThumbDataView.getSelectedIndexes();
              if (i.length >= 1) {
                stormwaterControlTypeVal = stormwaterControlTypeStore.getAt(i[0]).get('full');
              }

              var wqd = calcWQD(stormwaterControlTypeVal,loadReductionPctField.getValue()/100,performanceStore);
              var loadRemoved = calcLoadRemoved(stormwaterControlTypeVal,wqd,parcelInfoStore,performanceStore);
              var costFactor  = getBmpConstraintCostFactor(stormwaterControlConstraintComboBox.getValue(),stormwaterControlConstraintStore);
              var unitCost    = getBmpTypeUnitCost(stormwaterControlTypeVal,stormwaterControlTypeStore);
              var wqVolume    = calcWQVolume(parcelInfoStore,wqd);
              var totalCost   = costFactor * unitCost * wqVolume;
              unitCost        = totalCost / loadRemoved;

              this.setSource({
                 'Total Area (ac)'            : Math.round(parcelInfoStore.getAt(0).get('Total Area (ac)') * 100) / 100
                ,'Total Impervious Area (ac)' : Math.round(parcelInfoStore.getAt(0).get('Imperv Area (ac)') * 100) / 100
                ,'Water Quality Depth (in)'   : Math.round(wqd * 10000) / 10000
                ,'Load Removed (lb/yr)'       : Math.round(loadRemoved * 100) / 100
                ,'Stormwater Control Total Cost ($)'      : CommaFormatted(new String(Math.round(totalCost)))
                ,'Stormwater Control Unit Cost ($/lb/yr)' : CommaFormatted(new String(Math.round(unitCost)))
              });

              document.getElementById('recommendation').style.visibility = 'visible';
              var a = [];
              if (parcelInfoStore.getAt(0).get('Regulated') == 'True') {
                if (new RegExp(/^(C|D|C\/D|U)$/).test(parcelInfoStore.getAt(0).get('Hyd Soil Group'))) {
                  a.push('<font color="red">Low quality soil. Consider buying credits.</font>');
                }
                else if (loadReductionPctField.getValue() >= 65) {
                  if (unitCost <= 22000) {
                    a.push('<font color="green">None at this time.</font>');
                  }
                  else {
                    a.push('<font color="#cd853f"">Control with high unit cost. Consider lower cost Control.</font>');
                  }
                }
                else {
                  a.push('<font color="red">Not meeting reduction requirements. Raise the load reduction.</font>');
                }
              }
              else {
                if (new RegExp(/^(C|D|C\/D|U)$/).test(parcelInfoStore.getAt(0).get('Hyd Soil Group'))) {
                  a.push('<font color="red">Low quality soil. Consider buying credits.</font>');
                }
                else if (unitCost <= 22000) {
                  a.push('<font color="green">None at this time.</font>');
                }
                else {
                  a.push('<font color="#cd853f"">Control with high unit cost. Consider lower cost Control.</font>');
                }
              }
              document.getElementById('recommendationText').innerHTML = a.join('<br>');
            }
            ,'hide'      : function() {
              document.getElementById('recommendation').style.visibility = 'hidden';
              document.getElementById('recommendationText').innerHTML = 'None at this time.';
            }
          }
        });

        new Ext.Panel({
           border    : false
          ,height    : 530
          ,id        : 'solutionPanel'
          ,renderTo  : 'solution'
          ,html      : '<table><tr><td><h1>Select Stormwater Control Goals</h1> ' + goalsDiv.join('') + ' </td> <td> <h1>Select Stormwater Control (percent ranking by the Exchange based on site and goals)</h1> <div id="images-view"> </div> </td></tr><tr class="blueRow"><td><div id="finalSolution"> <h1>The Exchange Cost Analysis</h1> <div id="parcelResultsGrid"> </div> </div></td><td><div id="stormwaterControlCosts"> <table><tr><td><h1>Choose Design Criteria</h1> <div id="addlSiteConstraints"> </div> <span style="line-height:4px"><br></span> <div id="recommendation"> <h1>The Exchange Recommendation</h1> <span id="recommendationText" class="highlightTitle">None at this time.</span> </div> </td><td class="thumbTd"><h1>Stormwater&nbsp;Control&nbsp;Costs</h1><img class="thumbImg" src="images/stormwater_control_costs_graph_thumb.jpg" usemap="#controlCostsThumbMap"><map name="controlCostsThumbMap" id="controlCostsThumbMap"><area shape="rect" coords="135,92,151,110" href="javascript:showThumbDetailsWindow(\'Stormwater Control Costs\',\'<table><tr><td><img width=689 height=486 src=\\\'images/stormwater_control_costs_graph_full.jpg\\\'></td></tr></table>\',Ext.getCmp(\'solutionPanel\').getPosition()[0] - 30,Ext.getCmp(\'solutionPanel\').getPosition()[1] + 20,720)" alt="View larger graph" title="View larger graph"></area></map></td></tr></table> </div></td></tr><tr><td><a href="javascript:submitSolution()"><img style="margin-top:15px" alt="View solution summary" title="View solution summary" src="images/print_data_design-but.png"></a></td></tr></table>'
          ,listeners : {
            afterrender : function(panel) {
              for (var i in goals) {
                goals[i].render(i);
              }
              stormwaterControlThumbPanel.render('images-view');
              addlSiteConstraints.render('addlSiteConstraints');
              parcelResultsGrid.render('parcelResultsGrid');

              for (var i in goals) {
                goals[i].suspendEvents();
                goals[i].setValue(2);
                goals[i].resumeEvents();
              }
              checkGoalsSelected(goals,parcelInfoStore,stormwaterControlTypeStore);
              loadReductionPctField.setValue('');
              stormwaterControlConstraintComboBox.setValue('Partly developed area');
              stormwaterControlThumbDataView.select(0);
            }
          }
        });
      }

      // Take action when a goal is selected.
      function checkGoalsSelected(goals,parcelInfoStore,stormwaterControlTypeStore) {
        var possibleGoals = 0;
        var hits          = 0;
        for (var i in goals) {
          possibleGoals++;
          if (goals[i].items.get(0).getGroupValue() >= 1) {
            hits++;
          }
        }
        if (possibleGoals == hits) {
          stormwaterControlThumbPanel.enable();
          loadReductionPctField.enable();
          stormwaterControlConstraintComboBox.enable();
        }
        else {
          stormwaterControlThumbPanel.disable();
          loadReductionPctField.disable();
          stormwaterControlConstraintComboBox.disable();
          return;
        }
        // site eval
        stormwaterControlTypeStore.each(function(rec) {
          var ckConstraints       = 0;
          var possibleConstraints = 0;
          if (rec.get('min Dep2ResLyr (in)') <= parcelInfoStore.getAt(0).get('Dep2ResLyr (in)')) {
            ckConstraints++;
          }
          possibleConstraints++;
          if (rec.get('min Dep2HWT (in)') <= parcelInfoStore.getAt(0).get('Dep2HWT (in)')) {
            ckConstraints++;
          }
          possibleConstraints++;
          if (arrayIntersects(rec.get('Hyd Soil Group').split('/'),parcelInfoStore.getAt(0).get('Hyd Soil Group').split('/'))) {
            ckConstraints++;
          }
          possibleConstraints++;
          if (parcelInfoStore.getAt(0).get('Slope (%)')       <= rec.get('max Slope (%)')) {
            ckConstraints++;
          }
          possibleConstraints++;
          if (rec.get('min Total Area (ac)') <= parcelInfoStore.getAt(0).get('Total Area (ac)')) {
            ckConstraints++;
          }
          possibleConstraints++;
          if (parcelInfoStore.getAt(0).get('Total Area (ac)') <= rec.get('max Total Area (ac)')) {
            ckConstraints++;
          }
          possibleConstraints++;
          rec.set('suggestedConstraints',Math.round((ckConstraints / possibleConstraints) * 100));
          var ckGoals = 0;
          for (var i in goals) {
            if (goals[i].items.get(0).getGroupValue() <= rec.get(i)) {
              ckGoals++;
            }
          }
          rec.set('suggestedGoals',Math.round((ckGoals / possibleGoals) * 100));
          rec.set('overallScore'  ,Math.round((ckConstraints / possibleConstraints) * 50 + (ckGoals / possibleGoals) * 50));
          rec.commit();
        });
        stormwaterControlTypeStore.sort([{field : 'overallScore',direction : 'DESC'},{field : 'short',direction : 'ASC'}]);
        stormwaterControlThumbDataView.select(0);
      }

      function goResults(parcelInfoStore,stormwaterControlThumbDataView,loadReductionPctField,stormwaterControlConstraintComboBox) {
        if (parcelInfoStore.getCount() == 1
          && stormwaterControlThumbDataView.getSelectedIndexes().length == 1
          && loadReductionPctField.getValue() !== ''
          && stormwaterControlConstraintComboBox.getValue() !== ''
        ) {
          document.getElementById('finalSolution').style.visibility = 'visible';
          parcelResultsGrid.show();
        }
        else {
          document.getElementById('finalSolution').style.visibility = 'hidden';
        }
      }

      // Show a popup window w/ more stormwater details.
      function showThumbDetailsWindow(title,contents,x,y,w) {
        if (!Ext.getCmp('thumbDetailsWindow')) {
          thumbDetailsWindow = new Ext.Window({
             id          : 'thumbDetailsWindow'
            ,plain       : true
            ,defaults    : {border : false}
            ,autoHeight  : true
            ,listeners   : {
              move : function(p) {
                thumbDetailsWindowLastPos = p.getPosition();
              }
              ,beforeclose : function(p) {
                thumbDetailsWindowLastPos = p.getPosition();
              }
            }
          });
        }
        thumbDetailsWindow.setWidth(w);
        thumbDetailsWindow.removeAll();
        thumbDetailsWindow.setTitle(title != 'Stormwater Control Costs' ? title + ' Details' : title);
        thumbDetailsWindow.add({html : contents});
        if (!thumbDetailsWindowLastPos) {
          thumbDetailsWindow.setPosition(x,y);
        }
        else {
          thumbDetailsWindow.setPosition(thumbDetailsWindowLastPos);
        }
        thumbDetailsWindow.show();
        thumbDetailsWindow.doLayout();
        thumbDetailsWindow.syncShadow();
      }

      // Show a popup window w/ the solution summary.
      function submitSolution() {
        var stormwaterControlTypeVal;
        var i = stormwaterControlThumbDataView.getSelectedIndexes();
        if (i.length >= 1) {
          stormwaterControlTypeVal = stormwaterControlTypeStore.getAt(i[0]).get('full');
        }

        var loadCreditDeficit = Number((loadReductionPctField.getValue() / 100 - (parcelInfoStore.getAt(0).get('Regulated') == 'True' ? 0.65 : 0.10)) * parcelInfoStore.getAt(0).get('Total Load (lb/yr)')).toFixed(2);
        if (parcelInfoStore.getAt(0).get('Regulated') != 'True' && loadCreditDeficit < 0) {
          loadCreditDeficit = Number(0).toFixed(2);
        }
        new Ext.ux.ManagedIFrame.Window({
           defaultSrc  : 'popup.php'
             + '?subtitle0=Site Information'
             + '&parcelNum=' + cp.get('parcelNum')
             + '&ownerName=' + escape(parcelInfoStore.getAt(0).get('Owner Name'))
             + '&subtitle1=Average Soil Properties'
             + '&depthToHWTIn=' + Number(parcelInfoStore.getAt(0).get('Dep2HWT (in)')).toFixed(2)
             + '&depthToResLyrIn=' + Number(parcelInfoStore.getAt(0).get('Dep2ResLyr (in)')).toFixed(2)
             + '&hydSoilGroup=' + parcelInfoStore.getAt(0).get('Hyd Soil Group')
             + '&kSatInHr=' + Number(parcelInfoStore.getAt(0).get('KSat (in/hr)')).toFixed(2)
             + '&subtitle2=Land Use Areas'
             + '&impervAreaAc=' + Number(parcelInfoStore.getAt(0).get('Imperv Area (ac)')).toFixed(2)
             + '&uplandAreaAc=' + Number(parcelInfoStore.getAt(0).get('UpLand Area (ac)')).toFixed(2)
             + '&wetlandAreaAc=' + Number(parcelInfoStore.getAt(0).get('Wetland Area (ac)')).toFixed(2)
             + '&totalAreaAc=' + Number(parcelInfoStore.getAt(0).get('Total Area (ac)')).toFixed(2)
             + '&subtitle3=Total Phosphorus Loads'
             + '&pervLoadLbYr=' + Number(parcelInfoStore.getAt(0).get('Perv Load (lb/yr)')).toFixed(2)
             + '&impervLoadLbYr=' + Number(parcelInfoStore.getAt(0).get('Imperv Load')).toFixed(2)
             + '&totalLoadLbYr=' + Number(parcelInfoStore.getAt(0).get('Total Load (lb/yr)')).toFixed(2)
             + '&loadRemovedLbYr=' + parcelResultsGrid.getSource()['Load Removed (lb/yr)']
             + '&subtitle4=Stormwater Control Conceptual Design'
             + '&stormwaterControl=' + stormwaterControlTypeVal
             + '&loadReductionPct=' + loadReductionPctField.getValue()
             + '&waterQualirtyDepthIn=' + Number(parcelResultsGrid.getSource()['Water Quality Depth (in)']).toFixed(2)
             + '&subtitle5=Estimated Stormwater Control Construction Costs'
             + '&siteConstraint=' + stormwaterControlConstraintComboBox.getValue()
             + '&stormwaterControlUnitCostDollarLbYr=' + parcelResultsGrid.getSource()['Stormwater Control Unit Cost ($/lb/yr)']
             + '&stormwaterControlTotalCostDollar=' + parcelResultsGrid.getSource()['Stormwater Control Total Cost ($)']
             + '&subtitle6=Estimated Trading Credit/Deficit'
             + '&loadCreditDeficitLbYr=' + loadCreditDeficit
             + '&creditUnitValueDollarLbYr=' + parcelResultsGrid.getSource()['Stormwater Control Unit Cost ($/lb/yr)']
             + '&title=SUMMARY AND CONCEPTUAL DESIGN'
             + '&file=solution'
          ,focusOnLoad : true
          ,title       : name
          ,width       : 510
          ,height      : 400
          ,y           : 75
          ,bodyStyle   : 'background:white'
          ,constrainHeader : true
          ,modal           : true
          ,title           : 'Summary and Conceptual Design'
        }).show();
      }
    </script>

    <style>
<?php echo file_get_contents('css/data-view.css')?>
<?php echo file_get_contents('css/proSolution.css')?>
      #solutionDiv {
        width    : 860px;
        height   : 530px;
        position : relative;
      }
      #solution {
        width    : 860px;
        height   : 530px;
        top      : 0px;
        left     : 0px;
        position : absolute;
      }
    </style>

    <div id="site">
<?php include_once('header.php')?>
        <div id="content">

            <div class="home-screen clearfix">

                <div class="left-column" style="width: 500px;">
                    <h2 style="margin-bottom: 20px;">Select Solution</h2>
                                <p>Select Stormwater Control goals and type to determine the cost to meet the phosphorus reduction goal of 65% on your site.</p>
                    <div id="solutionDiv">
                      <div id="loading"><span id="loading-message">Loading. Please wait...</span></div>
                      <div id="solution"></div>
                    </div>
                        </div>
                        <div class="right-column">
	<div id="small_map"><img src="<?php echo $thumbnail?>"></div>
<?php
  if ($isRegistered) {
?>
	<p><label class="item first"><strong>Property Owner: </strong></label><label><?php echo substr($_COOKIE['ys-parcelOwner_Name'],2)?></label></p>
<?php
}
else {
?>
        <p><label class="item first"><strong>Property Address: </strong></label><?php echo substr($_COOKIE['ys-parcelPhys_Addr1'],2).', '.substr($_COOKIE['ys-parcelPhys_City'],2)?></label></p>
<?php
}
?>
	<p><label class="item"><strong>Impervious Area (acres): </strong></label><label><?php echo sprintf("%.2f",substr($_COOKIE['ys-parcelImperv_Area_(ac)'],2))?></label></p>
                        </div>
                        <div style="clear: both;">
                                <p style="margin-bottom: 0;">Click Next to continue to the trading page.</p>
                                <a href="?page=proLocation"><img src="images/back_but.png" style="vertical-align: top; margin-top: 20px;" alt="Back" title="Back" /></a>
                                                                                <a href="?page=proTrading"><img src="images/next_but.png" style="vertical-align: top; margin-left: 570px; margin-top: 20px;" alt="Next" title="Next" /></a>
                                                                        </div>

            </div>



        </div>
<?php include_once('footer.php')?>
    </div>
    <script type="text/javascript" src="./js/ext-3.4.0/adapter/ext/ext-base.js"></script>
    <script type="text/javascript" src="./js/ext-3.4.0/ext-all.js"></script>
    <script type="text/javascript" src="./js/miframe/multidom.js"></script>
    <script type="text/javascript" src="./js/miframe/mif.js"></script>
    <script type="text/javascript" src="./js/proCalcs.js"></script>
</body>
